<template>
  <el-dialog :visible.sync="dialog" :close-on-click-modal="false" :before-close="cancel"
             :title="isAdd ? '新增用户' : '编辑用户'" append-to-body width="700px">
    <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="100px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="form.username"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="enabled">
            <el-radio v-for="item in dicts" :key="item.id" v-model="form.enabled" :label="item.value">{{ item.label }}
            </el-radio>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="电话" prop="phone">
            <el-input v-model.number="form.phone"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="部门" prop="deptId">
            <treeselect v-model="deptId" :options="depts" style="width: 178px" placeholder="选择部门"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item style="margin-bottom: 0px;" label="角色" prop="roleIds">
            <el-select v-model="roleIds" multiple :multiple-limit=1
                       @change="roleChange"
                       placeholder="请选择">
              <el-option
                v-for="(item, index) in roles"
                :disabled="(level !== 1 && item.level <= level)||item.id===1"
                :key="item.name + index"
                :label="item.name"
                :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isMerchant">
        <el-col>
          <el-form-item style="margin-bottom: 0px;" label="所属商户" prop="merchantList">
            <el-cascader
              v-model="form.merchantList"
              :options="merchantOptions"
              :props="{ checkStrictly: true ,value	:'id'}"
              clearable></el-cascader>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="cancel">取消</el-button>
      <el-button :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
  import {getMerchant} from '@/api/business/merchantApi'
  import {add, edit} from '@/api/user'
  import {getDepts} from '@/api/dept'
  import {getAll, getLevel} from '@/api/role'
  import Treeselect from '@riophae/vue-treeselect'
  import '@riophae/vue-treeselect/dist/vue-treeselect.css'

  export default {
    components: {Treeselect},
    props: {
      isAdd: {
        type: Boolean,
        required: true
      },
      dicts: {
        type: Array,
        required: true
      }
    },
    data() {
      const validPhone = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入电话号码'))
        } else if (!this.isvalidPhone(value)) {
          callback(new Error('请输入正确的11位手机号码'))
        } else {
          callback()
        }
      }
      return {
        merchantRole: 2,
        isMerchant: false,
        roleIdMap: {},
        merchantOptions: [],
        dialog: false,
        loading: false,
        form: {
          username: '',
          email: '',
          enabled: 'false',
          roles: [],
          dept: {id: ''},
          phone: null,
          merchantList: undefined,
          merchantId: '',
        },
        roleIds: [],
        roles: [],
        depts: [],
        deptId: null,
        level: 3,
        rules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur'}
          ],
          email: [
            {required: true, message: '请输入邮箱地址', trigger: 'blur'},
            {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
          ],
          phone: [
            {required: true, trigger: 'blur', validator: validPhone}
          ],
          enabled: [
            {required: true, message: '状态不能为空', trigger: 'blur'}
          ],
          merchantList: [
            {required: true, message: '请选择所属商户', trigger: 'change'}
          ],
        }
      }
    },
    created() {
      this.getMerchant()
    },
    methods: {
      getMerchant() {
        getMerchant().then(res => {
          this.merchantOptions = res.content
        })
      },
      roleChange(i) {
        if (i && i.length > 0) {
          this.isMerchant = i[0] === 2;
        } else {
          this.isMerchant = false
        }
      },
      cancel() {
        this.resetForm()
      },
      doSubmit() {
        this.form.dept.id = this.deptId
        if (this.roleIds[0] !== 2) {
          this.form.merchantList = ''
          this.form.merchantId = ''
        }
        if (this.form.merchantList && this.form.merchantList.length > 0) {
          this.form.merchantId = this.form.merchantList[this.form.merchantList.length - 1]
          console.log(this.form.merchantId)
          this.form.merchantList = JSON.stringify(this.form.merchantList);
        }
        this.$refs['form'].validate((valid) => {
          if (valid) {
            if (this.deptId === null || this.deptId === undefined) {
              this.$message({
                message: '部门不能为空',
                type: 'warning'
              })
            } else if (this.roleIds.length === 0) {
              this.$message({
                message: '角色不能为空',
                type: 'warning'
              })
            } else {
              this.form.roles = []
              const _this = this
              this.roleIds.forEach(function (data, index) {
                const role = {id: data}
                _this.form.roles.push(role)
              })
              this.loading = true
              if (this.isAdd) {
                this.doAdd()
              } else this.doEdit()
            }
          } else {
            return false
          }
        })
      },
      doAdd() {
        add(this.form).then(res => {
          this.resetForm()
          this.$notify({
            title: '添加成功',
            message: '默认密码：123456',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.$parent.init()
        }).catch(err => {
          this.loading = false
          console.log(err.response.data.message)
        })
      },
      doEdit() {
        edit(this.form).then(res => {
          this.resetForm()
          this.$notify({
            title: '修改成功',
            type: 'success',
            duration: 2500
          })
          this.loading = false
          this.$parent.init()
        }).catch(err => {
          this.loading = false
          console.log(err.response.data.message)
        })
      },
      resetForm() {
        this.isMerchant = false
        this.showSearchCenter = false;
        this.showSearchBrand = false;
        this.showSearchFrontCenter = false;
        this.dialog = false
        this.$refs['form'].resetFields()
        this.deptId = null
        this.roleIds = []
        this.form = {
          username: '',
          email: '',
          enabled: 'false',
          roles: [],
          dept: {id: ''},
          phone: null,
          merchantList: undefined,
          merchantId: '',
        }
      },
      getRoles() {
        getAll().then(res => {
          this.roles = res
        }).catch(err => {
          console.log(err.response.data.message)
        })
      },
      getDepts() {
        getDepts({enabled: true}).then(res => {
          this.depts = res.content
        })
      },
      isvalidPhone(str) {
        const reg = /^1[3|4|5|6|7|8][0-9]\d{8}$/
        return reg.test(str)
      },
      getRoleLevel() {
        getLevel().then(res => {
          this.level = res.level
        }).catch(err => {
          console.log(err.response.data.message)
        })
      }
    }
  }
</script>

<style scoped>

</style>
